package com.ai.dao;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

import com.ai.dbutil.DBconn;
import com.ai.entity.Subscription;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class SubscpDao {
	public int subscribe(Subscription subscription) {
		Connection conn = DBconn.getInstance();
		int i = 0;
		String sql = "insert into Subscription (NAME, TIME) values (?,?)";
		PreparedStatement pstmt;
		try {
	        pstmt = (PreparedStatement) conn.prepareStatement(sql);
	        pstmt.setString(1, subscription.getName());
	        pstmt.setString(2, subscription.getTime());
	        i = pstmt.executeUpdate();
	        pstmt.close();
	        conn.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }	
	    return i;
	}
	/*
	 * if success returns the sum of affected rows in database which is positive,
	 * if no changes in database  returns 0,
	 * if cancel time is invalid returns -1
	 */
	public int cancel(Subscription subscription) {
		Connection conn = DBconn.getInstance();
		String time = subscription.getTime();
		Calendar now = Calendar.getInstance();
		Calendar subTime = Calendar.getInstance();
		subTime.set(Integer.parseInt(time.substring(0, 4)), 
				Integer.parseInt(time.substring(4, 6)),
				Integer.parseInt(time.substring(6, 8)),
				Integer.parseInt(time.substring(9, 11)) - 2,
				Integer.parseInt(time.substring(11, 13))
				);
		int i = 0;
		if(now.compareTo(subTime) < 0) {
			String sql = "delete from Subscription where NAME=? and TIME=?";
			PreparedStatement pstmt;
			try {
		        pstmt = (PreparedStatement) conn.prepareStatement(sql);
		        pstmt.setString(1, subscription.getName());
		        pstmt.setString(2, subscription.getTime());
		        i = pstmt.executeUpdate();
		        pstmt.close();
		        conn.close();
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		} else {
			i = -1; 
		}
	    return i;
	}
}
